import { master } from './master';
import './environment-hack';
import { AppModelService, SelectParamService } from '@manycore/pages-vm-api';
import { getCustomElements, getSelectedCustomModels, transformParamModelToParameters } from './util';
import { defaultProductId } from './constant';

// 配置中间件模型ID
IDP.Custom.DoorCoveringHardware.setProductId({ productId: defaultProductId });

IDP.Miniapp.view.defaultFrame.mount(IDP.Miniapp.view.mountPoints.main);

// 设置全屏展示
function setFrameSize() {
  const layout = IDP.UI.computeLayout();
  const width = 240;
  const height = layout.windowHeight - layout.topBar.height - layout.bottomBar.height - 60 - 25;
  IDP.Miniapp.view.setContainerOptions(IDP.Miniapp.view.defaultFrame, {
    draggable: true,
    resizable: false,
    position: {
      x: layout.windowWidth - width - 8,
      y: layout.topBar.height,
    },
  });
  IDP.Miniapp.view.defaultFrame.resize(width, height);
}

// 触发进入掩门五金模式
IDP.Custom.Mode.enter({
  mode: IDP.Custom.Mode.AppMode.DOOR_COVERING_HARDWARE,
});

// 监听模式内容变化时，自动触发事件
IDP.Events.on('IDP.Custom.DoorCoveringHardware.Mode', (option) => {
  master.getService(AppModelService)!.appMode.emit(option);
});

IDP.Events.on('IDP.Custom.DoorCoveringHardware.SelectedElementsChange', async (element) => {
  const elementIds = getCustomElements(element);
  const allModels = await getSelectedCustomModels(elementIds);

  // 处理当前选中模型数量
  master.getService(AppModelService)?.selectedModelCount.emit(elementIds.length);

  const option = IDP.Custom.DoorCoveringHardware.getOption();
  if (option?.hardwareModel === 'edit') {
    master.getService(SelectParamService)!.selectedParameters.emit(transformParamModelToParameters(allModels));
  }

  // 选中的预览图
  /*master
        .getService(SketchImageService)
        ?.sketchImage.emit(await getSelectedModelCoverImage(allModels));*/
});

// 监听模式退出时，自动退出小程序
IDP.Events.on('IDP.Custom.Mode.Exit', (mode) => {
  if (mode === IDP.Custom.Mode.AppMode.DOOR_COVERING_HARDWARE) {
    IDP.Miniapp.exit();
  }
});

setFrameSize();
master.start();
